package cn.danger.com.model.action;

import android.content.Context;
import android.text.TextUtils;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.danger.com.model.entity.MyUser;
import cn.danger.com.model.listener.OnCommonListener;
import cn.danger.com.util.Check;
import cn.danger.com.util.Constants;
import cn.danger.com.util.MyNetManager;

/**
 * Created by 俊 on 2016/12/29.
 */
public class ModifyNickNameModelImpl implements ModifyNickNameModel {

    private Context context;

    public ModifyNickNameModelImpl(Context context) {
        this.context = context;
    }

    @Override
    public void updateNickName(String nick_name, final OnCommonListener listener) {
        if (!TextUtils.isEmpty(nick_name)) {
            if (new MyNetManager(context).isNetworkAvailable()) {
                MyUser new_user = new MyUser();
                new_user.setNick_name(nick_name);
                MyUser user = BmobUser.getCurrentUser(MyUser.class);
                if (nick_name.equals(user.getNick_name())) {
                    listener.onError(Constants.NICK_NAME_IS_USING);
                } else {
                    if (user != null) {
                        new_user.update(user.getObjectId(), new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    listener.onSuccess(null);
                                } else {
                                    e.printStackTrace();
                                    if (Check.checkByCode(e.getErrorCode()) == null) {
                                        listener.onError(Constants.FAIL_TO_UPDATE_NICK_NAME);
                                    } else {
                                        listener.onError(Check.checkByCode(e.getErrorCode()));
                                    }
                                }
                            }
                        });
                    } else {
                        listener.onError(Constants.LOGIN_IS_VALID);
                    }
                }
            } else {
                listener.onError(Constants.NETWORK_IS_NOT_AVAILABLE);
            }
        } else {
            listener.onError(Constants.NICK_NAME_IS_EMPTY);
        }
    }
}
